<h1>Administracija Proizvođača</h1>
<?= $this->Html->link("+ Novi proizvođač", "/admin_partners/create") ?>

<button class="updatOrder" style="float:right;display:none" onclick="saveOrder()">Ažuriraj redosled</button>
<table>
    <tr>
        <th>Naziv</th>
        <th>Sajt</th>
        <th>Slika</th>
        <th width="1%"></th>
        <th></th>
    </tr>
    <? foreach($allPartners as $p): ?>
    <tr partnerId="<?= $p['Partner']['id'] ?>">
        <td><?= $this->Html->link($p['Partner']['name'], '/admin_partners/edit/'.$p['Partner']['id']) ?></td>
        <td><?= $this->Html->link($p['Partner']['url'], null, array('target'=>'_blank')) ?></td>
        <td><?= $this->Html->image('partners/'.preg_replace('/\.(.*?)$/', '.hover.$1', $p['Partner']['image']))?></td>
        <td>
            <?= $this->Html->link('obriši', '/admin_partners/delete/' . $p['Partner']['id'], array("onclick"=>"return confirm('Da li želite da obrišete proizvođača?')")) ?>
        </td>
        <td class="handle"></td>
    </tr>
    <? endforeach; ?>
</table>

<script type="text/javascript">
$(function(){
    $('table').sortable({
        items:  'tr',
        handle: 'td.handle',
        forcePlaceholderSize: true,
        forceHelperSize: true,
        revert: 'invalid',
        stop: function(e, ui) {
            $('.updatOrder').show();
        }
    })
})

function saveOrder() {
    var positions = [];
    $('table').find('tr').each(function(index){
        id = parseInt($(this).attr('partnerId'));
        if (id>0) {
            positions.push({
               id: id,
               position: index 
            });
        }
    });
    
    $.ajax({
        url: '/admin_partners/reorder',
        data: {positions: positions},
        beforeSend: function() {
            $('table').addClass('loading');
        },
        complete: function(req) {
            $('table').removeClass('loading');
            $('button.updatOrder').hide();
            alert(req.responseText);
        }
    })
}
</script>